package com.lu.pojo.datastructures.sparsearray;

/**
 * @author luzhenfang
 * @date 2020 05 30
 * @description 稀疏数组压缩(模拟棋盘游戏存档)
 */
public class SparseArray {
    public static void main(String[] args) {
        int chessArr1[][] = new int[11][11];
        // 模拟棋盘 对局 1 白棋 2 黑棋 0 空
        chessArr1[1][2] = 1;
        chessArr1[2][2] = 2;
        System.out.println("压缩前");
        for (int[] ints : chessArr1) {
            for (int i : ints) {
                if(i==1){
                    System.out.print("√ ");
                }else if(i==2){
                    System.out.print("X  ");
                }else{
                    System.out.print(i +"  ");
                }
            }
            System.out.println();

        }
        // 得到非0个数
        int sum =0;
        for (int[] ints : chessArr1) {
            for (int anInt : ints) {
                if (anInt!=0){
                    sum++;
                }
            }
        }
        System.out.println("sum="+sum);
        // 创建稀疏数组
        int[][] sparseArr = new int[sum + 1][3];
        // row
        sparseArr[0][0]=11;
        // col
        sparseArr[0][1]=11;
        // count
        sparseArr[0][2]=sum;
        // 遍历数组 将 非0 的数据放到 sparseArr 中
        int count =0;
        for (int i = 0; i < chessArr1.length; i++) {
            for (int j = 0; j < chessArr1[0].length; j++) {
                if(chessArr1[i][j]!=0){
                    count++;
                    sparseArr[count][0]=i;
                    sparseArr[count][1]=j;
                    sparseArr[count][2]=chessArr1[i][j];
                }
            }
        }
        // 输出稀疏数组
        System.out.format("%-4s %-4s %-5s\n","row","col","value");
        System.out.println("---------------");
        for (int[] ints : sparseArr) {
            for (int anInt : ints) {
                System.out.format("%-5d",anInt);
            }
            System.out.println();

        }
        // 稀疏数组 转 棋盘
        System.out.println("恢复后");
        int[][] chessArr2 = new int[sparseArr[0][0]][sparseArr[0][1]];
        for (int i = 1; i < sparseArr.length; i++) {
            chessArr2[sparseArr[i][0]][sparseArr[i][1]]=sparseArr[i][2];
        }
        for (int[] ints : chessArr2) {
            for (int anInt : ints) {
                if(anInt==1){
                    System.out.print("√ ");
                }else if(anInt==2){
                    System.out.print("X  ");
                }else{
                    System.out.print(anInt +"  ");
                }
            }
            System.out.println();
        }
    }
}
